import {
  CallHandler,
  ExecutionContext,
  Inject,
  Injectable,
  NestInterceptor,
  Logger,
  RequestTimeoutException,
} from '@nestjs/common';
import {
  Observable,
  map,
  tap,
  catchError,
  throwError,
  timeout,
  TimeoutError,
} from 'rxjs';
import { Reflector } from '@nestjs/core';

@Injectable()
export class TimeInterceptor implements NestInterceptor {
  constructor() {}

  @Inject(Reflector)
  private reflector: Reflector;

  private readonly logger = new Logger(TimeInterceptor.name);

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log(context.getClass(), context.getHandler());
    const startTime = Date.now();
    // 判断请求方式 context.getType() http, ws, rpc

    console.log(
      'time interceptor',
      this.reflector.getAll('roles', [
        context.getHandler(),
        context.getClass(),
      ]),
    );

    return next.handle().pipe(
      timeout(3000),
      catchError((err) => {
        if (err instanceof TimeoutError) {
          console.log('超时===', err);
          return throwError(() => new RequestTimeoutException());
        }
        // this.logger.error('啦啦啦===', err.message, err.stack);
        return throwError(() => err);
      }),

      // map((data) => {
      //   this.logger.log('hahah====', data);
      //   return JSON.stringify({
      //     code: 200,
      //     message: 'success',
      //     data,
      //     time: Date.now() - startTime,
      //   });
      // }),
      tap(() => {
        this.logger.log(`log time: ${Date.now() - startTime}ms`);
        console.log(`time: ${Date.now() - startTime}ms`);
      }),
    );
  }
}
